#include "weatherfetcher.h"
#include "weatherTool.h"
#include <QNetworkRequest>
#include <QMessageBox>
#include <QDebug>

WeatherFetcher::WeatherFetcher(QObject *parent)
    : QObject(parent)
{
    mNetworkManager = new QNetworkAccessManager(this);
    connect(mNetworkManager, &QNetworkAccessManager::finished, this, &WeatherFetcher::onNetworkResponse);
}



void WeatherFetcher::getWeatherInfo(QString cityName) {
    QString citycode = WeatherTool::getCityCode(cityName);
    if(cityName.isEmpty()){
        emit weatherError("您还未输入要查询的天气");
        return;
    }

    QString url = "http://t.weather.itboy.net/api/weather/city/" + citycode;
    mNetworkManager->get(QNetworkRequest(QUrl(url)));
}

void WeatherFetcher::onNetworkResponse(QNetworkReply* reply) {
    if (reply->error() == QNetworkReply::NoError) {
        QByteArray data = reply->readAll();
        // qDebug() << data.data();
        emit weatherDataReceived(data);
    }
    else {
        emit weatherError("获取天气信息失败！");
    }
    reply->deleteLater();
}
